let homepage = document.querySelector(".homepage");
let header = document.querySelector("header");
let addBox = document.querySelector(".add");
let openBox = document.querySelector(".openBox");
let showing = [homepage, header];
let timer;

function timeShow(time) { // 时间处理
    let date = new Date(time);
    let month = (date.getMonth() + 1).toString().padStart(2, 0);
    function pad(num) {
        return num.toString().padStart(2, 0);
    }
    let res = `${date.getFullYear()}-${month}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    return res;
}

function changeHeadShowDiv(sw) {
    let addDiv = header.querySelector("#addDiv");
    let openDiv = header.querySelector("#openDiv");
    if (sw) {
        addDiv.classList.add("isChecked");
        openDiv.classList.remove("isChecked");
    } else {
        addDiv.classList.remove("isChecked");
        openDiv.classList.add("isChecked");
    }
}

function changeShowBox(bigBox, h) { // 改变显示的盒子
    showing[0].style.display = "none";
    if (h) showing[1].style.display = "block";
    else showing[1].style.display = "none";
    showing[0] = bigBox;
    showing[0].style.display = "block";
    let divs = header.querySelectorAll(".left > div");
    divs[2].className = "";
    divs[3].className = "";
    clearInterval(timer);
}

function toAdd(e) { // 跳转到添加时间胶囊页面
    let arr = [];
    let errTips = addBox.querySelectorAll(".errTip");
    arr[0] = addBox.querySelectorAll("input");
    arr[1] = addBox.querySelectorAll("textarea");
    for (let els of arr) {
        for (let item of els) {
            item.value = "";
        }
    }
    let openTimeInput = addBox.querySelector("#openTimeInput");
    openTimeInput.value = timeShow(Date.now());

    for (let item of errTips) {
        item.style.display = "none";
    }
    addBox.children[0].style.display = "block";
    addBox.children[1].style.display = "none";
    changeShowBox(addBox, true);
    changeHeadShowDiv(true);
}

function toOpen(e) { // 跳转到打开时间胶囊页面
    changeShowBox(openBox, true);
    let sections = openBox.querySelectorAll(".openBox > section");
    for (let item of sections) {
        item.style.display = "none";
    }
    changeHeadShowDiv(false);
}

function toDiary(e) { // 跳转到胶囊日记页面
    location.href = '../../html/ys/index.html';
}

function toHomepage(e) { // 跳转到时间胶囊首页
    changeShowBox(homepage);
}

// 首页的js
(() => {
    let buttonBox = homepage.querySelector(".buttonBox");
    let putEl = buttonBox.children[0];
    let openEl = buttonBox.children[1];
    let bottomBox = homepage.querySelector(".bottom");

    putEl.addEventListener("click", toAdd);
    openEl.addEventListener("click", toOpen);
    bottomBox.children[0].addEventListener("click", function (e) {
        toOpen();
        // 自动打开介绍胶囊 4o0x-rzua-cwp4-9quf
        let input = openBox.querySelector("#keyInput");
        input.value = "4o0x-rzua-cwp4-9quf";
        openBox.querySelector("button").click();
    })
    bottomBox.children[1].addEventListener("click", toDiary);
})();

// 头部的js
(() => {
    let leftSection = header.querySelector(".left");
    leftSection.children[0].addEventListener("click", toHomepage);
    leftSection.children[1].addEventListener("click", toHomepage);
    leftSection.children[2].addEventListener("click", toAdd);
    leftSection.children[3].addEventListener("click", toOpen);

    let right = header.querySelector(".maxwidth > div");
    right.addEventListener("click", toDiary);
})();

// 添加胶囊部分
function showErr(el, msg) {
    el.textContent = msg;
    el.style.display = "block";
}
function clearErrTip(el) {
    el.style.display = "none";
}
(() => {
    let addBtn = addBox.querySelector("button");
    addBtn.addEventListener("click", addCapsule);
    async function addCapsule(e) {
        let name = addBox.querySelector("#nameInput").value.trim();
        let email = addBox.querySelector("#emailInput").value.trim();
        let openTime = addBox.querySelector("#openTimeInput").value.trim();
        let content = addBox.querySelector("#contentArea").value.trim();
        let tip = addBox.querySelector("#tipArea").value.trim();
        let errTips = addBox.querySelectorAll(".errTip");
        let canSent = true;
        if (!name) {
            canSent = false;
            showErr(errTips[0], "名字 必须填写.");
        } else clearErrTip(errTips[0]);
        if (!email) {
            canSent = false;
            showErr(errTips[1], "邮箱 必须填写.");
        } else {
            let reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
            if (reg.test(email)) clearErrTip(errTips[0]);
            else {
                canSent = false;
                showErr(errTips[1], "邮箱 必须是一个有效的电子邮箱地址.");
            }
        }
        if (!openTime) {
            canSent = false;
            showErr(errTips[2], "打开时间 必须填写.");
        } else {
            openTime = Date.parse(openTime);
            if (openTime) {
                clearErrTip(errTips[2]);
            } else {
                canSent = false;
                showErr(errTips[2], "打开时间 格式不正确");
            }
        }
        if (!content) {
            canSent = false;
            showErr(errTips[3], "内容 必须填写.");
        } else clearErrTip(errTips[3]);

        let res;
        if (canSent) {
            res = await axios({
                url: "/api/timecapsule/create",
                method: "POST",
                data: {
                    authorId: localStorage.getItem("userId"),
                    username: name,
                    tip,
                    content,
                    email,
                    openTime
                }
            })
            if (res.data.code) {
                alert(res.data.msg);
                return;
            }
            let addOkBox = addBox.querySelector(".addOkBox");
            let writingBox = addBox.querySelector(".writingBox");
            let addKeyInput = addOkBox.querySelector("#addKeyInput");
            addKeyInput.value = res.data.data;
            writingBox.style.display = "none";
            addOkBox.style.display = "block";
        }
    }
})();

// jtm2-b0u1-svqd-dtsj

(() => { // 打开胶囊部分
    let inputBox = openBox.querySelector(".inputBox");
    let btn = inputBox.querySelector("button");

    btn.addEventListener("click", openCapsuleFun);
})();

async function openCapsuleFun(e) {
    let keyInput = openBox.querySelector("#keyInput");
    let key = keyInput.value.trim();
    let nocapsule = openBox.querySelector(".nocapsule");
    let capsuleContentBox = openBox.querySelector("#capsuleContent");
    let cannot = openBox.querySelector(".cannot");
    let res = await axios({
        url: "/api/timecapsule",
        params: { key }
    })
    if (res.data.code) { // 0 //  1
        alert(res.data.msg);
        return;
    }
    let data = res.data.data;
    if (data) { // 有data ， 找到胶囊
        if (!data.content) { // 胶囊不能打开
            let outTime = Math.floor((Date.parse(data.openTime) - Date.now()) / 1000);
            cannot.innerHTML = `
            <h2>这颗胶囊未到提取时间，不能打开。</h2>
            <section class="timeTip">
                打开时间在 <b>${timeShow(data.openTime)}</b>，距离现在<span>${outTime}</span>秒。
            </section>
            <section class="content">
                <p><b>${data.username}</b>给你留的提示信息：</p>
                <span>${data.tip}</span>
            </section>
            `
            nocapsule.style.display = "none";
            capsuleContentBox.style.display = "none";
            cannot.style.display = "block";
            interval(outTime);
        } else {
            capsuleContentBox.children[0].textContent = `${data.username} 在 ${timeShow(data.openTime)} 对你说：`
            capsuleContentBox.children[1].innerHTML = data.content;
            nocapsule.style.display = "none";
            cannot.style.display = "none";
            capsuleContentBox.style.display = "block";
            clearInterval(timer);
        }
    } else { // data值为null 没找到胶囊key
        capsuleContentBox.style.display = "none";
        cannot.style.display = "none";
        nocapsule.style.display = "block";
        clearInterval(timer);
    }
}

function interval(num){
    let cannot = openBox.querySelector(".cannot");
    let span = cannot.querySelector(".timeTip span");
    timer = setInterval(()=>{
        span.textContent = --num;
    } , 1000);
}